import axios from 'axios'
import vue from "vue";
import { isArray, isIpOrLocalAddr } from "@/utils/validate";

const service = axios.create({
  timeout: 60 * 1000,
})

// Request interceptors
service.interceptors.request.use(
  (config) => {
    if (config.params) { //数组转换
      let params: any = {}
      for (const key in config.params) {
        if (Object.prototype.hasOwnProperty.call(config.params, key)) {
          const item = config.params[key];
          if (isArray(item)) {
            params[key] = item.join(',')
          } else {
            params[key] = item || ""
          }
        }
      }
      config.params = params
    }
    if (config.data) { // 将null转成空字符串
      let params: any = {}
      for (const key in config.params) {
        if (Object.prototype.hasOwnProperty.call(config.params, key)) {
          params[key] == JSON.parse(JSON.stringify(config.params[key])) || ""
        }
      }
      config.params = params
    }
    return config
  },
  (error) => {
    // console.log(error) // for debug
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    // console.log(response)
    const res:any = response.data
    if (res instanceof Blob) {
      return res
    }
    //旧的学工api使用res.state，新的接口使用res.code，Blob表示是文件资源
    if (res.state || +res.code == 200 || res instanceof Blob) {
      return res.data
    }

    vue.prototype.$toast.error(res.message)
    if (+res.code === 401) {
      if (!isIpOrLocalAddr(location.hostname)) {
        return location.reload()
      }
    }
    return Promise.reject(new Error(res.message || 'Error'))
  },
  (error) => {
    let message = error.message
    // if (error.response.data && error.response.data.message) {
    //   message += "<br/>" + error.response.data.message
    // }
    vue.prototype.$toast.error(message || 'Error')
    return Promise.reject(error)
  }
)

export default service
